#!/usr/bin/env bash

function prepare_software() {
  apt-get update
  apt-get install -y vim wget git cmake gcc python3 python3-pip jq
  pip config set global.index-url https://mirrors.huaweicloud.com/repository/pypi/simple
}

function prepare_npm_soft() {
  apt-get install -y npm
}

function prepare_bingo() {
  cd ~
  git clone https://gitcode.com/openUBMC/bingo.git
  cd ~/bingo
  sh install_local.sh
}

function prepare_git() {
  git_username=$1
  git_token=$2

  git config --global credential.helper store
  git config --global user.name "$git_username"
  echo "https://${git_username}:${git_token}@gitcode.com" >~/.git-credentials
  chmod 600 ~/.git-credentials

}

function prepare_conan() {
  conan_username=$1
  conan_password=$2
  conan remote add openubmc_dev https://devrepo.devcloud.cn-north-4.huaweicloud.com/artgalaxy/api/conan/cn-north-4_ad268a13b93c480087c8a1e4b0fe8b15_conan_1/
  conan user "${conan_username}" -p="${conan_password}" -r=openubmc_dev
  conan config set general.revisions_enabled=1
  conan remote list
}

function prepare_sdk() {
  cd ~
  git clone https://gitcode.com/openUBMC/manifest.git
  cd ~/manifest
  bingo build -t install_sdk || true
}

function build_component() {
  path=$1
  cd "${path}"
  echo "start to build(${path})..."
  not_dt_comp=("mdb_interface" "webui" "vpd")
  echo "构建执行bingo build -bt debug --stage rc"
  bingo build -bt debug --stage rc -nc
  echo "构建执行bingo build -bt debug --stage stable"
  bingo build -bt debug --stage stable -nc
  echo "构建执行bingo build -bt release --stage rc"
  bingo build -bt release --stage rc -nc
  echo "构建执行bingo build -bt release --stage stable"
  bingo build -bt release --stage stable -nc

  if ! echo "${not_dt_comp[@]}" | grep -qw "$package"; then
    echo " '$package' 不在数组中"
    echo "构建执行bingo build -bt dt --stage rc"
    bingo build -bt dt --stage rc -nc
    echo "构建执行bingo build -bt dt --stage stable"
    bingo build -bt dt --stage stable -nc
  fi

}

function upload_conan() {
  path=$1
  cd "${path}"
  echo "start to upload conan(${path})..."
  remote_name="openubmc_dev"
  json_file="mds/service.json"
  name=$(jq -r '.name' "$json_file")
  version=$(jq -r '.version' "$json_file")
  package_name="$name/$version"
  search_result=$(conan search "$package_name")
  if [ -z "$search_result" ]; then
    echo "未找到包: $package_name"
    exit 1
  fi
  packages=$(echo "$search_result" | grep "$package_name@" | tr -d ' ')
  for package in $packages; do
    echo "正在上传包: $package"
    conan upload "$package" -r "$remote_name" --all
  done
}

function prepare_conan_cache() {
    echo "准备conan缓存"
    wget --show-progress=off https://dailybuild.openubmc.cn/conan_cache/conan_cache.tar.gz && \
    tar -xf conan_cache.tar.gz -C ~ && \
    rm conan_cache.tar.gz
}